/*
 * Copyright 2009 Alberto Gimeno <gimenete at gmail.com>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package siena.dbslayer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

import siena.SienaException;
import siena.logging.SienaLogger;
import siena.logging.SienaLoggerFactory;

public class URLConnector implements Connector {

	private URL backend;
	private HttpURLConnection connection;
	
	private SienaLogger logger = SienaLoggerFactory.getLogger(URLConnector.class);

	public void configure(Properties p) {
		try {
			this.backend = new URL(p.getProperty("backend"));
		} catch (MalformedURLException e) {
			throw new SienaException(e);
		}
	} // configure.

	public void close() throws IOException {
	} // close.

	public void connect(RequestMethod method, boolean useMethodTunneling)
			throws IOException {

		this.connect(method, useMethodTunneling, "");
	} // connect.

	public void connect(RequestMethod method, boolean useMethodTunneling,
			Object addionalParameters) throws IOException {

		URL url = this.backend;

		if ((null != addionalParameters)
				&& (addionalParameters.toString().trim().length() > 0)) {

			url = new URL(url + addionalParameters.toString());
			if (this.logger.isInfoEnabled()) {
			  
				this.logger.info("Using addional parameters URL: " + url);
			}
		}
		
		if (this.logger.isInfoEnabled()) {
		  
			this.logger.info("URL: " + url);
		}

		this.connection = HttpURLConnection.class.cast(url
				.openConnection());
		
		this.connection.setRequestProperty("Content-type",
				"application/x-www-form-urlencoded;charset=UTF-8");
		this.connection.setDoOutput(true);
		this.connection.setDoInput(true);
		this.connection.setInstanceFollowRedirects(true);

		if (useMethodTunneling) {

			this.connection.setRequestMethod(RequestMethod.POST.getName());
			this.connection.setRequestProperty("X-HTTP-Method-Override", method
					.getName());

		} else {

			this.connection.setRequestMethod(method.getName());
		}
	} // connect.

	public InputStream getInputStream() throws IOException {
		return connection.getInputStream();
	}

	public OutputStream getOutputStream() throws IOException {
		return connection.getOutputStream();
	}

	public void connect() throws IOException {

		this.connect(RequestMethod.POST, false);
	}

} // E:O:F:URLConnector.
